package com.contexticon.filehandling;

import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import javax.swing.table.DefaultTableModel;

public class TranscriptFileWriter {

	public static void writeModelToSrt(DefaultTableModel model, String filePath) {
		
		//open the file
		try {
		FileWriter outFile = new FileWriter(filePath);
		PrintWriter out = new PrintWriter(outFile);

		int noRows = model.getRowCount();
		for (int r=0; r<(noRows-1); r++) {
			
			if ((model.getValueAt(r, 0)!=null)&&(model.getValueAt(r, 1)!=null)&&(model.getValueAt(r, 2)!=null)) {
				out.println(r+1);
				String startTime = convertTimeToString(((Float) model.getValueAt(r, 0)));
				String endTime = convertTimeToString(((Float) model.getValueAt(r, 1)));

				out.println(startTime + "\t-->\t" + endTime);
				String utterance = (String) model.getValueAt(r, 2);
			
				out.println(utterance);
				out.println("");
			}
		}

		System.out.println("Wrote transcript to "+filePath);
		out.close();
		}
		catch(Exception e) {
			System.out.println("Failed to open the file");
			System.out.println(e.toString());
		}
		
	}
	
	
	private static String convertTimeToString(Float msTotal) {
		
		

		int hr = (int) Math.floor(msTotal/(1000*60*60));
		int min = (int) Math.floor(msTotal/(1000*60) % 60);
		int sec = (int) Math.floor(msTotal/(1000) % 60);
		// take 3 last digits
		int ms = (int) (msTotal % 1000);


		return (String.format("%02d", hr) + ":" + String.format("%02d", min) 
				+ ":" + String.format("%02d", sec) +"," + String.format("%02d", ms) );
	}

	public static void main(String[] args) {

		//writeModelToSrt(null,"testFile");
		
		//System.out.println(convertTimeToString(new Float(15000399)));
		
	}
	
}
